package com.yc.RSS;

import com.yc.url.Test2_url_urlconnection_httpurlconnection;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.security.Key;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author zwei
 * @create 2024-07-23 20:43
 */
public class RSSDataCapturer extends DefaultHandler {
    private static Logger logger = Logger.getLogger(Test2_url_urlconnection_httpurlconnection.class);

    private List<CommonInformationItem> list;
    private CommonInformationItem item;
    private String source;  //RSS源名称
    private int status;     //存当前解析到什么标记
    private StringBuffer buffer;    //存文本
    private DateFormat df=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);

    public RSSDataCapturer(String name) {
        this.source = name;     //RSS源名
        buffer=new StringBuffer();
    }
    public static void main(String[] args) throws ParserConfigurationException, SAXException, ParseException {
//        String path=System.getProperty("user.dir");
//        System.out.println(path);
//        path=path+"";
        String path="https://www.zhihu.com/rss";
        RSSDataCapturer rdc=new RSSDataCapturer("知乎RSS");
        List<CommonInformationItem>list=rdc.load(path);
        for (CommonInformationItem item:list){
            System.out.println(list);
        }
        System.out.println("总共得到："+list.size()+"条新闻");
    }
    /**
     * 解析xml对应的RSS源  得到item集合  返回
     *
     * @param source
     * @return
     */
    public List<CommonInformationItem> load(String source) throws ParserConfigurationException, SAXException {
        list=new ArrayList<>();
        //SAX解析流程代码
        //1.创建SAX解析器
        SAXParserFactory spf=SAXParserFactory.newInstance();
        //2.注册事件处理器
        SAXParser parser=spf.newSAXParser();
        //3.解析xml文件
        try {
            parser.parse(source,this);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
    //解析xml文件的开头
    @Override
    public void startDocument() throws SAXException {
        logger.debug("文档的开头，开始解析，创建list");
        list=new ArrayList<>();
        super.startDocument();
    }

    //解析到xml文件的结尾
    @Override
    public void endDocument() throws SAXException {
        logger.debug("文档结尾");
        super.endDocument();
    }
    private final int STATUS_TITLE=1;
    private final int STATUS_LINK=2;
    private final int STATUS_DESCRIPTION=3;
    private final int STATUS_PUBDATE=4;
    private final int STATUS_GUID=5;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        logger.debug("元素的开头："+uri+"\t"+localName+"\t"+qName+"\t"+attributes);
        //记录当前解析的是什么
        if (item!=null&&qName.equalsIgnoreCase("title")){
            status=STATUS_TITLE;
        } else if (item!=null&&qName.equalsIgnoreCase("link")) {
            status=STATUS_LINK;
        } else if (item!=null&&qName.equalsIgnoreCase("description")) {
            status=STATUS_DESCRIPTION;
        } else if (item!=null&&qName.equalsIgnoreCase("pubDate")) {
            status=STATUS_PUBDATE;
        } else if (item!=null&&qName.equalsIgnoreCase("guid")) {
            status=STATUS_GUID;
        } else if (qName.equalsIgnoreCase("item")) {
            item=new CommonInformationItem();
            item.setSource(this.source);
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        logger.debug("元素的结束："+uri+"\t"+localName+"\t"+qName+"\t");
        //判断你解析的是哪个结束因素
        if (item!=null&&qName.equalsIgnoreCase("title")){
            item.setTitle(buffer.toString());
            status=0;
        } else if (item!=null&&qName.equalsIgnoreCase("link")) {
            item.setLink(buffer.toString());
            status=0;
        } else if (item!=null&&qName.equalsIgnoreCase("description")) {
            item.setDescription(buffer);
            status=0;
        } else if (item!=null&&qName.equalsIgnoreCase("pubDate")) {
            item.setTextDate(buffer.toString());
            try {
                item.setDate(df.parse(buffer.toString().trim()));
            } catch (ParseException e) {
                logger.error(e);
            }
            status=0;
        } else if (item!=null&&qName.equalsIgnoreCase("guid")) {
            item.setId(buffer.toString());
            status=0;
        } else if (qName.equalsIgnoreCase("item")) {
            if (item.getId()==null){
                item.setId(item.getDescription().hashCode() + "");
            }
            list.add(item);
            item=null;
        }
        buffer=new StringBuffer();
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String txt=new String( ch,start, length);
        logger.debug("解析到了文字："+new String(ch,start,length  ));
        buffer.append(txt);
    }
}


